<template>
  <div class="home">
    <!-- 筛选 -->
    <div class="search_content">
      <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow @click-left="$router.go(-1)" />
      <form action>
        <van-search v-model="requestParams.codeNo" placeholder="请输入车架号或者车牌号" shape="round" @search="initData" @clear="clearSearch" />
      </form>
      <div class="search_item">
        <van-dropdown-menu :close-on-click-outside="false">
          <van-dropdown-item title="品牌展厅" ref="brandRef">
            <div class="searchbox timebox">
              <van-field v-model="requestParams.brandName" name="品牌" label="品牌" placeholder="请选择" input-align="right" :rules="[{ required: true }]" right-icon="arrow" @click="handleSelect('brandId', 'brandName')" readonly />
              <van-field v-model="requestParams.showOrgName" name="展厅" label="展厅" input-align="right" placeholder="请选择" :rules="[{ required: true }]" right-icon="arrow" @click="handleSelect('showOrgId', 'showOrgName')" readonly />
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleBrandReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('brandRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="入库时间" ref="saleRef">
            <div class="searchbox">
              <div class="flex">
                <van-field class="time_item" v-model="requestParams.stockStartDate" label :placeholder="'开始时间'" input-align="right" readonly @click="handleSelectTime('stockStartDate')" />-
                <van-field class="time_item" v-model="requestParams.stockEndDate" label :placeholder="'结束时间'" input-align="right" readonly @click="handleSelectTime('stockEndDate')" />
              </div>

              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleSearchReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('saleRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="筛选" ref="statusRef">
            <div class="searchbox">
              <van-field name="radio" label="是否生成销售合同" input-align="right" label-width="170px">
                <template #input>
                  <van-radio-group v-model="requestParams.isGenContract" direction="horizontal">
                    <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <div class="title">库存状态</div>

              <div class="insureList">
                <div class="insure_item" :class="stockIndex == index ? 'active' : ''" v-for="(item, index) in carStockBillStatusList" :key="index" @click="handleSearchSelect(index)">{{ item.name }}</div>
              </div>
              <van-field name="radio" label="是否寄售车辆" input-align="right" label-width="170px">
                <template #input>
                  <van-radio-group v-model="requestParams.isJySale" direction="horizontal">
                    <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
                  </van-radio-group>
                </template>
              </van-field>

              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleRaidoReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('statusRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>

        <!-- 服务顾问下拉 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>
        <!-- 时间选择 -->
        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @cancel="onCancelDate" @confirm="onConfirmDate" :formatter="formatter" />
        </van-popup>
      </div>
    </div>

    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadData" v-if="recordList && recordList.length != 0">
        <div class="carList">
          <div class="carItem" v-for="(item, index) in recordList" :key="index" @click="goDetail(item)">
            <div class="carItem_name">{{ item.carModel }}</div>
            <div class="carItem_con">
              <div class="carItem_con_lt">
                <img v-if="item.imageCol && item.imageCol[0]" :src="item.imageCol[0].imageUrl" />
                <div v-else class="noimg">暂无图片</div>
              </div>
              <div class="carItem_con_rt">
                <div class="carItem_data">
                  <div class="carItem_data_txt">{{ item.carNo ? item.carNo : "-" }}</div>
                  <div class="carItem_data_txt">{{ item.regDate ? item.regDate : "-" }}</div>
                  <div class="carItem_data_txt">{{ item.carMile ? item.carMile : "-" }}万公里</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">车架号：</div>
                  <div class="carItem_txt">{{ item.vinCode ? item.vinCode : "-" }}</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">采购展厅：</div>
                  <div class="carItem_txt">{{ item.showOrgName ? item.showOrgName : "-" }}</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">采购人员：</div>
                  <div class="carItem_txt">{{ item.purName ? item.purName : "-" }}</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">入库日期：</div>
                  <div class="carItem_txt">{{ item.stockDate ? item.stockDate : "-" }}</div>
                </div>

                <div class="carItem_data">
                  <div class="carItem_label">库龄：</div>
                  <div class="carItem_txt">{{ item.stockDays ? `${item.stockDays}天` : "-" }}</div>
                </div>
              </div>
            </div>
            <div class="carItem_footer">
              <div class="carStatus" v-if="item.billStatus">{{ item.billStatus }}</div>
            </div>
          </div>
        </div>
        <!-- <div class="carList">
          <div
            class="carItem"
            v-for="(item, index) in recordList"
            :key="index"
            @click="goDetail(item)"
          >
            <div class="carItem_name">{{ item.carModel }}</div>
            <div class="carItem_con">

              <div class="carItem_con_rt">
                <div class="carItem_data">
                  <div class="carItem_data_txt">{{ item.carNo }}</div>
                  <div class="carItem_data_txt">{{ item.regDate }}</div>
                  <div class="carItem_data_txt">{{ item.carMile }}公里</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">车架号：</div>
                  <div class="carItem_txt">{{ item.vinCode }}</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">入库日期：</div>
                  <div class="carItem_txt">{{ item.stockDate }}</div>
                </div>
                <div class="carItem_data">
                  <div class="carItem_label">采购展厅：</div>
                  <div class="carItem_txt">{{ item.showOrgName }}</div>
                </div>
              </div>
            </div>
            <div class="carItem_footer">
              <div class="carStatus">{{ item.billStatus }}</div>
            </div>
          </div>
        </div>-->
      </van-list>
      <van-empty class="noContent" description="暂无数据" v-else />
    </van-pull-refresh>

    <!-- <div class="addBtn">
      <div
        class="footerBtn orderItem_filebox"
        @click="handleAdd"
      >
        新增线索
      </div>
    </div>-->
  </div>
</template>

<script>
import { Search, DropdownMenu, DropdownItem, Empty, Dialog } from "vant";
import commonApi from "@/api/commonApi";
import { getCookies } from "@/utils/util.js";
import sellManageApi from "@/api/sellManageApi";

export default {
  name: "buyManage",
  components: {
    Search,
    DropdownMenu,
    DropdownItem,
    Empty,
    Dialog
  },
  data() {
    return {
      value: "",
      carCouponList: [
        { name: "是", code: 1, check: false },
        { name: "否", code: 0, check: false }
      ],
      saleTypeList: [],
      statusList: [
        { name: "已处理", code: 1, check: false },
        { name: "未处理", code: 2, check: false }
      ],

      recordList: [
        // {
        //   billId: '', //单据ID
        //   carNo: '', //车牌号
        //   vinCode: '', //车架号
        //   carModel: '', //二手车车型
        //   billStatus: '', //单据状态
        //   regDate: '', //初次登记日期
        //   stockDate: '', //入库日期
        //   showOrgName: '', //采购展厅
        //   carMile: '', //行驶里程数
        // },
      ],
      columns: [],
      showSelectPicker: false,
      requestParams: {
        codeNo: "", //车架号，非必填，String
        pageNo: 1, //页码，非必填，String
        userId: "", //用户ID，必填，String
        orgId: "", //登录组织Id，必填，String
        stockStartDate: "", //入库开始时间，非必填，String
        stockEndDate: "", //入库结束时间，非必填，String
        brandId: "", //品牌ID，非必填，String
        showOrgId: "", //展厅ID，非必填，String
        isGenContract: "", //是否生成销售合同，非必填，String
        billStatus: "", //库存状态，非必填，String
        isJySale: "", //是否寄售车辆，非必填，String
        brandName: "",
        showOrgName: ""
      },
      carCouponIndex: null,

      repairCenterList: [
        { name: "厦门路虎", code: 1 },
        { name: "厦门捷豹", code: 2 }
      ],
      serviceList: [
        { name: "黄某某", code: 1 },
        { name: "张某某", code: 2 }
      ],
      delayList: [
        { name: "是", billId: 1, check: false },
        { name: "否", billId: 0, check: false }
      ],
      creatList: [
        { name: "是", billId: 1, check: false },
        { name: "否", billId: 0, check: false }
      ],
      defeatList: [
        { name: "是", billId: 1, check: false },
        { name: "否", billId: 0, check: false }
      ],

      delayIndex: null,
      creatIndex: null,
      defeatIndex: null,
      showTransmitFlag: false,
      timeField: "",
      showPickerDate: false,
      currentDate: new Date(),
      list: [],
      // 分页参数
      loading: false,
      finished: false,
      refreshing: false,
      isLoadData: false,

      field: "",
      fieldName: "",
      fixCenterList: [],
      oneBillStatusList: [],
      twoBillStatusList: [],
      isflagList: [
        { name: "是", value: 1 },
        { name: "否", value: 0 }
      ],
      brandList: [],
      showOrgList: [],
      carStockBillStatusList: [],
      stockIndex: null
    };
  },

  mounted() {
    // this.getShowOrgByUser()
    this.initData();
    this.getCarStockBillStatusList();
  },

  methods: {
    // 初始化列表
    initData() {
      this.requestParams.pageNo = 1;
      this.loadData();
    },
    loadData() {
      if (this.isLoadData) return;
      this.isLoadData = true;
      this.loading = true;
      this.finished = false;
      // console.log(this.isLoadData);
      sellManageApi
        .secondHandCarFacade({
          ...this.requestParams,
          method: "getCarStockList"
        })
        .then(res => {
          if (!this.recordList || this.recordList.length < 1) {
            this.getBrandByUser();
          }
          if (this.requestParams.pageNo == 1) {
            this.recordList = res.data || [];
          } else {
            this.recordList = this.recordList.concat(res.data || []);
          }
          this.requestParams.pageNo += 1;

          if (res.data && res.data.length < 10) {
            this.finished = true;
            this.isLoadData = true;
          }
          this.isLoadData = false;
          this.loading = false;
        });
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.recordList = [];
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.refreshing = false;
      this.initData();
    },
    // 计算库龄
    countDay(time) {
      var date1 = new Date(time);
      var date2 = new Date();
      var Difference_In_Time = date2.getTime() - date1.getTime();
      var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
      console.log(Difference_In_Days);
      return parseInt(Difference_In_Days);
    },

    // 获取库存列表
    getCarStockBillStatusList() {
      commonApi
        .getEnums({
          key: "carStockBillStatus",
          userId: this.requestParams.userId
        })
        .then(res => {
          // if (res.data) {
          // res.data = [{value:1,name:1},{value:2,name:2}]
          this.carStockBillStatusList = res.data;
          // }
        });
    },
    // 获取品牌
    getBrandByUser() {
      sellManageApi
        .secondHandCarFacade({
          userId: this.userId,
          orgKey: "brandAll", // orgkey
          method: "getShowOrgByUser"
        })
        .then(res => {
          if (res.data) {
            this.brandList = res.data;
          }
        });
    },
    // 获取展厅
    getShowOrgByUser() {
      sellManageApi
        .secondHandCarFacade({
          userId: this.userId,
          method: "getShowOrgByBandId",
          brandId: this.requestParams.brandId
        })
        .then(res => {
          if (res.data) {
            this.showOrgList = res.data;
          }
        });
    },
    // 格式化多选数据
    formatCheckData(data) {
      data.forEach(item => {
        item.check = false;
      });
      return data;
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "outUser") {
        this.columns = [
          { name: "服务人员1", value: 1 },
          { name: "服务人员2", value: 2 }
        ];
      } else if (field == "fixCenterId") {
        this.columns = this.fixCenterList;
      } else if (field == "brandId") {
        this.columns = this.brandList;
      }
      this.field = field;
      this.fieldName = fieldName;
    },

    // 筛选是否
    handleCarSelect(index) {
      this.carCouponIndex = index;
    },
    // 筛选重置
    handleSelectReset() {
      this.requestParams.taskPersonId = "";
    },
    // 品牌展厅重置
    handleBrandReset() {
      this.requestParams.brandId = "";
      this.requestParams.brandName = "";
      this.handleHallReset();
    },
    // 品牌展厅重置
    handleHallReset() {
      this.requestParams.showOrgId = "";
      this.requestParams.showOrgName = "";
    },
    // 入库时间重置
    handleSearchReset() {
      this.requestParams.stockEndDate = "";
      this.requestParams.stockStartDate = "";
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.requestParams[this.field] = value.billId;
      this.requestParams[this.fieldName] = value.name;
      if (this.field == "brandId") {
        this.getShowOrgByUser();
        this.handleHallReset();
      }
      this.showSelectPicker = false;
    },
    // 筛选重置
    handleRaidoReset() {
      this.requestParams.isJySale = "";
      this.requestParams.isGenContract = "";
      this.requestParams.billStatus = "";
      this.stockIndex = null;
      // this.carStockBillStatusList.forEach((item) => {
      //   item.check = false
      // })
    },

    onConfirm(ref) {
      this.$refs[ref].toggle();
      if (ref == "saleRef") {
        let checkList = [];
        this.carStockBillStatusList.forEach(el => {
          if (el.check) {
            checkList.push(el.value);
          }
          this.requestParams.salesType = checkList.join(";");
        });
      }
      if (this.stockIndex || this.stockIndex == 0) {
        this.requestParams.billStatus = this.carStockBillStatusList[
          this.stockIndex
        ].value;
      }
      this.initData();
    },
    // 时间确认
    onConfirmDate() {
      this.requestParams[
        this.timeField
      ] = `${this.value1}-${this.value2}-${this.value3}`; // 字符串拼接 结果入2020-07-03
      this.onCancelDate();
    },
    onCancelDate() {
      this.showPickerDate = false;
    },

    // 日期组件自定义格式
    formatter(type, value) {
      if (type === "year") {
        this.value1 = value; // 可以拿到当前点击的数值
        return `${value}年`;
      } else if (type === "month") {
        this.value2 = value;
        return `${value}月`;
      }
      this.value3 = value;
      return `${value}日`;
    },

    // 详情
    goDetail(data) {
      localStorage.setItem("billId", data.billId);
      this.$router.push({
        path: "/inventoryManageDetail"
        // query: { billId: data.billId },
      });
    },

    // 顶部筛选选择数据
    handleSearchSelect(index) {
      this.stockIndex = index;
    },

    // 时间筛选
    handleSelectTime(field) {
      this.timeField = field;
      this.showPickerDate = true;
    },
    clearSearch() {
      this.requestParams.codeNo = "";
      this.initData();
    }
  }
};
</script>

<style lang="less" scoped="">
body {
  background: #f3f3f3;
}
.search_content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}
.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 5px 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}
.full {
  width: 100% !important;
}
.searchbox {
  padding: 15px;

  .title {
    font-size: 15px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
    padding-top: 10px;
  }
  .insureList {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .insure_item {
      border: 1px solid #999;
      text-align: center;
      padding: 0.15rem 0rem;
      width: 30%;
      box-sizing: border-box;
      // margin-right: 5px;
      font-size: 13px;
      border-radius: 3px;
      color: #666;
      margin-bottom: 10px;
      margin-right: 5%;
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        border: 1px solid #f65e07;
        color: #f65e07;
      }
    }
  }
  .insureBtn {
    display: flex;
    justify-content: right;
    margin-top: 20px;
    .resetBtn {
      padding: 0 20px;
      margin-right: 10px;
    }
    .confirmBtn {
      padding: 0 20px;
    }
  }
}

.carList {
  padding-top: 148px;
  margin: 10px;
  overflow: hidden;
  .carItem {
    padding: 15px;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 15px;
    .carItem_name {
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f6f6f6;
      position: relative;
      font-size: 14px;
      font-weight: bold;
      line-height: 15px;
    }
    .carItem_con {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      align-content: center;
      align-self: center;
      .carItem_con_lt {
        width: 1.6rem;
        height: 1.6rem;
        margin-right: 10px;
        img {
          width: 100%;
          height: 100%;
          display: block;
          border-radius: 5px;
        }
        .noimg {
          text-align: center;
          width: 1.6rem;
          height: 1.6rem;
          line-height: 1.6rem;
          border-radius: 5px;
          // border: 1px solid #ccc;
          color: #999;
          font-size: 13px;
          background: #f4f4f4;
        }
      }
      .carItem_con_rt {
        .carItem_data {
          display: flex;
          align-items: center;
          font-size: 13px;
          margin-bottom: 5px;
          &:last-child {
            margin-bottom: 0;
          }
          .carItem_data_txt {
            border-right: 1px solid #999;
            color: #333;
            padding-right: 5px;
            margin-right: 5px;
            &:last-child {
              border-right: none;
            }
          }
          .carItem_label {
            color: #333;
          }
          .carItem_txt {
            color: #333;
          }
        }
      }
    }
    .carItem_footer {
      display: flex;
      justify-content: flex-end;
      border-top: 1px solid #f6f6f6;
      margin-top: 5px;
      padding-top: 10px;
      align-items: center;
      .acount {
        font-size: 13px;
        color: #333;
        .txt {
          color: #e31f1f;
        }
        .txt1 {
          color: #666;
        }
      }
      .carStatus {
        background: #35bc04;
        color: #fff;
        border-radius: 3px;
        padding: 5px 0.15rem;
        font-size: 12px;
      }
    }
  }
}
.orderList {
  padding-top: 2rem;
  margin: 10px;
  overflow: hidden;
  // padding-bottom: 1.5rem;
  .taskCheck {
    margin-right: 5px;
  }
  .orderItem {
    padding: 15px;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 15px;
    width: 100%;
    .orderItem_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f6f6f6;
      position: relative;
      .orderItem_lt {
        .carNo {
          font-size: 15px;
          color: #333;
          margin-right: 10px;
          font-weight: bold;
        }

        .carStatus {
          background: #35bc04;
          color: #fff;
          border-radius: 4px;
          padding: 5px 10px;
          font-size: 12px;
          text-align: center;
          width: 50px;
          margin-top: 5px;
        }
      }
      .orderItem_rt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;
        color: #666;
        font-size: 14px;

        .txt {
          font-size: 14px;
          color: #161616;
        }
        .icon-tel {
          color: #fff;
          background: #35bc04;
          font-size: 16px;
          padding: 5px;
          border-radius: 50%;
          margin-right: 10px;
        }
        .icon-wx {
          color: #409eff;
          font-size: 33px;
        }
      }
    }
    .orderItem_content {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: center;
      .orderItem_data {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 50%;
        margin-bottom: 10px;
        font-size: 14px;
        box-sizing: content-box;
        color: #333;
        .order_label {
          font-size: 14px;
          color: #333;
          width: 1.8rem;
        }
        .txt {
          font-size: 14px;
          color: #666;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &.time {
          width: 100%;
        }
      }
    }
    .orderItem_footer {
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #f6f6f6;
      padding-top: 10px;
      .orderItem_status {
        background: #35bc04;
        color: #fff;
        font-size: 12px;
        padding: 0.08rem 0.15rem;
        border-radius: 3px;
      }
    }
    .orderItem_file {
      background: #ebebeb;
      color: #333;
      border-radius: 5px;
      padding: 10px 0;
      text-align: center;
      width: 100%;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      .file_item {
        width: 33.33%;
        border-right: 1px solid #ccc;
        .icon-tel {
          font-size: 17px;
          color: #35bc04;
          margin-right: 5px;
        }
        .icon-mileage {
          font-size: 20px;
          color: #409eff;
          margin-right: 5px;
          position: relative;
          top: 2px;
        }
        .icon-gw {
          font-size: 20px;
          color: #409eff;
          margin-right: 5px;
          position: relative;
          top: 2px;
        }
        &:last-child {
          border: none;
        }
      }
    }
  }
}
.addBtn {
  position: fixed;
  bottom: 40px;
  width: 100%;
  z-index: 1;
  .footerBtn {
    width: 140px;
    margin: auto;
    text-align: center;
    font-size: 14px;
    padding: 12px 0rem;
    border-radius: 50px;
  }
  .orderItem_filebox {
    margin: auto;
    background: #409eff;
    color: #fff;
  }
  .comfirmBtn {
    background: #409eff;
    color: #fff;
  }
  .cancelBtn {
    border: 1px solid #ccc;
    color: #999;
    background: #fff;
  }
}
.noContent {
  margin-top: 100px;
}
</style>
